package com.misyi.designpattern.composite;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 没有使用组合模式
 *
 * @author licong
 * @date 2021-09-14 下午4:41
 */
public class CompositePatternDemo {

    public static void main(String[] args) {
        Department leafDept1 = new Department("叶子部门1");
        Department leafDept2 = new Department("叶子部门2");
        Department leafDept3 = new Department("叶子部门3");

        Department subDept1 = new Department("子部门1");
        subDept1.addChildDept(leafDept1);
        subDept1.addChildDept(leafDept2);
        Department subDept2 = new Department("子部门2");
        subDept2.addChildDept(leafDept3);

        Department parentDept = new Department("父部门");
        parentDept.addChildDept(subDept1);
        parentDept.addChildDept(subDept2);

        parentDept.remove();
    }

    @Data
    public static class Department {
        private String name;
        private List<Department> children = new ArrayList<>();

        public Department(String name) {
            this.name = name;
        }

        public void addChildDept(Department dept) {
            this.children.add(dept);
        }

        public void remove() {
            // 此处采用组合模式, 属于一种递归思想
            if (children.size() > 0) {
                for (Department child : children) {
                    child.remove();
                }
            }
            System.out.println("删除了部门[" + name + "]");
        }
    }

}
